import 'package:craze/common/index.dart';
import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';

class ChatListView extends StatefulWidget {
  const ChatListView({super.key});

  @override
  State<ChatListView> createState() => _ChatListViewState();
}

class _ChatListViewState extends State<ChatListView> {
  final AuthStore _authStore = getIt<AuthStore>();
  final ChatStore _chatStore = getIt<ChatStore>();
  final UserService _userService = getIt<UserService>();
  bool _isLoading = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadChats();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 页面每次依赖变化时刷新，保证未读状态实时
    _loadChats();
  }

  Future<void> _loadChats() async {
    if (!mounted) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      await _chatStore.loadUserChats();
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = "Failed to load chats: ${e.toString()}";
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Custom title bar
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Icon(
                        MyIcons.iconBack,
                        color: Colors.white,
                        size: 20.sp,
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: Text(
                          'Chat',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 22.sp,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                            fontWeight: FontWeight.w400,
                            height: 1.36,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () async {
                        await _chatStore.markAllAsRead();
                        await _loadChats();
                      }, // 一键已读
                      child: Icon(
                        MyIcons.iconClean,
                        color: Colors.white,
                        size: 24.sp,
                      ),
                    ),
                  ],
                ),
              ),

              // Horizontal avatar list
              SizedBox(height: 15.h),
              Observer(
                builder: (_) {
                  if (_isLoading && _chatStore.chats.isEmpty) {
                    return SizedBox(
                      height: 90.h,
                      child: Center(
                        child: CircularProgressIndicator(color: Colors.white),
                      ),
                    );
                  }

                  return SizedBox(
                    height: 90.h,
                    child: ListView(
                      scrollDirection: Axis.horizontal,
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      children: _buildRecentChatsAvatars(),
                    ),
                  );
                },
              ),

              SizedBox(height: 20.h),

              // Chat list
              Expanded(
                child: Observer(
                  builder: (_) {
                    if (_isLoading && _chatStore.chats.isEmpty) {
                      return Center(
                        child: CircularProgressIndicator(color: Colors.white),
                      );
                    }

                    if (_errorMessage != null) {
                      return Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.error_outline,
                              color: Colors.white,
                              size: 48.sp,
                            ),
                            SizedBox(height: 16.h),
                            Text(
                              _errorMessage!,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                              ),
                              textAlign: TextAlign.center,
                            ),
                            SizedBox(height: 16.h),
                            ElevatedButton(
                              onPressed: _loadChats,
                              child: Text('Retry'),
                            ),
                          ],
                        ),
                      );
                    }

                    if (_chatStore.chats.isEmpty) {
                      return Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.chat_bubble_outline,
                              color: Colors.white,
                              size: 48.sp,
                            ),
                            SizedBox(height: 16.h),
                            Text(
                              'There is no chat record',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                              ),
                            ),
                          ],
                        ),
                      );
                    }

                    return ListView.builder(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      itemCount: _chatStore.chats.length,
                      itemBuilder: (context, index) {
                        return _buildChatItemFromModel(_chatStore.chats[index]);
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  List<Widget> _buildRecentChatsAvatars() {
    if (!_authStore.isLoggedIn || _chatStore.chats.isEmpty) {
      return [];
    }

    // 按最后消息时间排序
    final sortedChats = List.of(_chatStore.chats)
      ..sort((a, b) => b.lastMessageTime.compareTo(a.lastMessageTime));

    // 只显示前5个最近的聊天
    final recentChats = sortedChats.take(5).toList();

    return recentChats.map((chat) {
      // 获取聊天名称和头像
      String name;
      String imageUrl;
      bool isGroup = chat.isGroupChat;
      final unreadCount =
          chat.unreadCountPerUser[_authStore.currentUser?.id ?? ''] ?? 0;
      bool hasUnread = unreadCount > 0;

      if (isGroup) {
        name = chat.groupName ?? 'Group';
        imageUrl = chat.groupAvatar ?? MyImages.touxiang1;
      } else {
        // 在私聊中找到对方用户
        final otherUserId = chat.participantIds.firstWhere(
          (id) => id != _authStore.currentUser!.id,
          orElse: () => '',
        );

        final otherUser = _userService.getUserById(otherUserId);
        name = otherUser?.name ?? 'Unknown';
        imageUrl = otherUser?.avatar ?? MyImages.touxiang1;
      }

      return Padding(
        padding: EdgeInsets.only(right: 24.w),
        child: GestureDetector(
          onTap: () {
            _navigateToChat(chat, unreadCount);
          },
          child: Column(
            children: [
              Stack(
                children: [
                  // Avatar
                  Container(
                    width: 58.w,
                    height: 58.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(100.r),
                        topRight: Radius.circular(100.r),
                        bottomLeft: Radius.circular(30.r),
                        bottomRight: Radius.circular(100.r),
                      ),
                      image: DecorationImage(
                        image: AssetImage(imageUrl),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),

                  // Group icon if it's a group chat
                  if (isGroup)
                    Positioned(
                      right: 0,
                      bottom: 0,
                      child: Container(
                        width: 18.w,
                        height: 18.w,
                        decoration: const BoxDecoration(
                          color: Colors.blue,
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                          child: Icon(
                            Icons.group,
                            color: Colors.white,
                            size: 12.sp,
                          ),
                        ),
                      ),
                    ),

                  // Notification dot if there are unread messages
                  if (hasUnread)
                    Positioned(
                      right: 2.w,
                      top: 2.h,
                      child: Container(
                        width: 10.w,
                        height: 10.w,
                        decoration: const BoxDecoration(
                          color: Colors.amber,
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                ],
              ),

              SizedBox(height: 5.h),

              // Name
              Container(
                constraints: BoxConstraints(maxWidth: 56.w),
                child: Text(
                  name,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                    fontFamily: GoogleFonts.inter().fontFamily,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ),
      );
    }).toList();
  }

  Widget _buildChatItemFromModel(ChatModel chat) {
    // 获取聊天名称和头像
    String name;
    String imageUrl;
    bool isGroup = chat.isGroupChat;

    if (isGroup) {
      name = chat.groupName ?? 'Group';
      imageUrl = chat.groupAvatar ?? MyImages.touxiang1;
    } else {
      // 在私聊中找到对方用户
      final otherUserId = chat.participantIds.firstWhere(
        (id) => id != _authStore.currentUser!.id,
        orElse: () => '',
      );

      final otherUser = _userService.getUserById(otherUserId);
      name = otherUser?.name ?? 'Unknown';
      imageUrl = otherUser?.avatar ?? MyImages.touxiang1;
    }

    // 获取最后一条消息
    final lastMessageId = chat.lastMessageId;
    final ChatService chatService = getIt<ChatService>();
    final messages = chatService.getMessagesByChat(chat.id);

    String messagePreview = '';
    bool isEmoji = false;
    String? emojiName;

    if (messages.isNotEmpty) {
      final lastMessage = messages.last;
      if (lastMessage.isEmoji) {
        isEmoji = true;
        emojiName = lastMessage.emojiPath?.split('/').last.split('.').first;
        messagePreview = lastMessage.content;
      } else {
        messagePreview = lastMessage.content;
      }
    }

    // 格式化时间
    String timeText = _formatTime(chat.lastMessageTime);
    // 计算未读数
    int unreadCount =
        chat.unreadCountPerUser[_authStore.currentUser?.id ?? ''] ?? 0;

    return InkWell(
      onTap: () {
        _navigateToChat(chat, unreadCount);
      },
      borderRadius: BorderRadius.circular(10.r),
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        child: Row(
          children: [
            // Avatar with possible group icon
            Stack(
              children: [
                Container(
                  width: 52.w,
                  height: 52.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.rectangle,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(200.r),
                      topRight: Radius.circular(200.r),
                      bottomLeft: Radius.circular(30.r),
                      bottomRight: Radius.circular(200.r),
                    ),
                    image: DecorationImage(
                      image: AssetImage(imageUrl),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),

                // Group icon if it's a group chat
                if (isGroup)
                  Positioned(
                    right: 0,
                    bottom: 0,
                    child: Container(
                      width: 18.w,
                      height: 18.w,
                      decoration: const BoxDecoration(
                        color: Colors.blue,
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Icon(
                          Icons.group,
                          color: Colors.white,
                          size: 12.sp,
                        ),
                      ),
                    ),
                  ),
              ],
            ),

            SizedBox(width: 15.w),

            // Chat info
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Username
                  Text(
                    name,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 5.h),
                  // Message preview
                  Text(
                    isEmoji ? '[${emojiName ?? 'emoji'}]' : messagePreview,
                    style: TextStyle(
                      color: Colors.white.withAlpha(178),
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w400,
                      fontFamily: GoogleFonts.inter().fontFamily,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),

            // Time and unread count
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                // Timestamp
                Text(
                  timeText,
                  style: TextStyle(
                    color: Colors.white.withAlpha(178),
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                    fontFamily: GoogleFonts.inter().fontFamily,
                  ),
                ),

                SizedBox(height: 5.h),

                // Unread count if any
                if (unreadCount > 0)
                  Container(
                    padding: EdgeInsets.all(5.w),
                    decoration: const BoxDecoration(
                      color: Colors.amber,
                      shape: BoxShape.circle,
                    ),
                    child: Text(
                      unreadCount.toString(),
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 10.sp,
                        fontWeight: FontWeight.bold,
                        fontFamily: GoogleFonts.inter().fontFamily,
                      ),
                    ),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 格式化时间的辅助方法
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inSeconds < 60) {
      return 'Just now';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} minutes ago';
    } else if (difference.inHours < 24) {
      return '${difference.inHours} hours ago';
    } else if (difference.inDays < 7) {
      return '${difference.inDays} days ago';
    } else {
      return DateFormat('MM-dd').format(dateTime);
    }
  }

  // 导航到聊天页面
  void _navigateToChat(ChatModel chat, int unreadCount) async {
    // 标记消息为已读
    if (unreadCount > 0) {
      await _chatStore.markMessagesAsRead(chat.id);
    }

    // 导航到聊天详情页
    if (chat.isGroupChat) {
      GoRouter.of(context).push('/group-chat/${chat.id}');
    } else {
      GoRouter.of(context).push('/chat/${chat.id}');
    }
  }
}
